package cn.itcast.nems.common.mybatisplus;

import cn.itcast.nems.common.tenant.TenantInfo;
import cn.itcast.nems.common.tenant.TenantInfoHolder;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.List;

/**
 * author: yong.li
 * create: 2023-08-17 14:24:20
 **/
public class TenantInterceptor extends TenantLineInnerInterceptor {
    public TenantInterceptor(final List<String> ignoreTables, final String tenantIdColumn) {
        super(new TenantLineHandler() {

            @Override
            public Expression getTenantId() {
                final Integer tenantId = TenantInfoHolder.getTenantInfo().map(TenantInfo::tenantId).orElse(0);
                return new LongValue(tenantId);
            }

            @Override
            public boolean ignoreTable(String tableName) {
                return ignoreTables.contains(tableName);
            }

            @Override
            public String getTenantIdColumn() {
                return tenantIdColumn;
            }
        });
    }
}
